package com.aliyun.dingtalk.util;

import com.aliyun.dingtalkworkflow_1_0.Client;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceHeaders;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceRequest;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponse;
import com.aliyun.dingtalkworkflow_1_0.models.GetProcessInstanceResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description //TODO
 * @Date 2025/3/24 16:14
 * @Author 郭建波
 **/
@Service
public class DDUtils {

    private static RestTemplate restTemplate = new RestTemplate();
//    @Autowired
//    private static RestTemplate restTemplate;

    @Value("${spslids}")
    private static String spslids;


    public static Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }


    // 分页获取审核通过的审批实例
    private static List<Map<String, Object>> getApprovedInstances(String accessToken, Long page, Long maxResults) {
        String url = "https://api.dingtalk.com/v1.0/workflow/processes/instanceIds/query";
        HttpHeaders headers = new HttpHeaders();
        headers.set("x-acs-dingtalk-access-token", accessToken);

        Map<String, Object> request = new HashMap<>();
        request.put("processCode", spslids);
        request.put("startTime", System.currentTimeMillis() - 24 * 60 * 60 * 100000); // 最近2400小时
        request.put("nextToken", page); // 分页大小
        request.put("maxResults", maxResults); // 分页大小

        List<Map<String, Object>> instances = new ArrayList<>();
        while (true) {
            HttpEntity<Map> entity = new HttpEntity<>(request, headers);
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);
            Map<String, Object> result = response.getBody();

            Map<String, Object> resultMap = (Map<String, Object>) response.getBody().get("result");
            if (resultMap.get("nextToken") == null) break;
            instances.addAll((List) resultMap.get("list"));
            request.put("nextToken", resultMap.get("nextToken")); // 分页大小
        }
        return instances;
    }


    // 分页获取审核通过的审批实例
    public static GetProcessInstanceResponse getSingleInstance(String accessToken, String processInstanceId) throws Exception {

        Client client = DDUtils.createClient();
        GetProcessInstanceHeaders getProcessInstanceHeaders = new GetProcessInstanceHeaders();
        getProcessInstanceHeaders.xAcsDingtalkAccessToken = accessToken;
        GetProcessInstanceRequest getProcessInstanceRequest = new GetProcessInstanceRequest()
            .setProcessInstanceId(processInstanceId);
        try {
            GetProcessInstanceResponse processInstanceWithOptions = client.getProcessInstanceWithOptions(getProcessInstanceRequest, getProcessInstanceHeaders, new RuntimeOptions());
            return processInstanceWithOptions;

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }


        return null;
    }






    public static void main(String[] args) throws Exception {
        GetProcessInstanceResponse singleInstance = getSingleInstance("8ea9d4871aa23e848ff3e40222d57363", "ma1LXm-9Rl6282jFk6z2Ng09891742798465");

        GetProcessInstanceResponseBody body = singleInstance.getBody();
        GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult result = body.getResult();
        String title = result.getTitle();
        System.out.println(title);


    }

}
